#!usr/bin/python3
import sys
import getopt
import os
import shutil

"""
用于划分文件，将文件下的所有图片分开存储到指定文件夹下
"""


def partitionFile(originPath, targetPath, size):
    if not os.path.exists(originPath):
        print("原始路径不存在")
        exit(1)
    if not os.path.exists(targetPath):
        print("目标路径不存在")
        exit(1)
    if size <= 0:
        print("大小错误")
        exit(1)
    currentIndex = 0
    currentPage = 0
    currentPath = targetPath + "/" + str(currentPage)
    if not os.path.exists(currentPath):
        os.mkdir(currentPath)

    for root, dirs, files in os.walk(originPath):
        for file in files:
            if file[0] == ".":
                continue
            filePath = os.path.join(root, file)  # 文件路径
            if currentIndex < size:
                shutil.copy(filePath, currentPath)
            else:
                currentIndex = 0
                currentPage = currentPage + 1
                currentPath = targetPath + "/" + str(currentPage)
                if not os.path.exists(currentPath):
                    os.mkdir(currentPath)
                shutil.copy(filePath, currentPath)
            print("复制", filePath, "到", currentPath)
            currentIndex = currentIndex + 1


def main(argv):
    dec = """用于划分文件，将文件下的所有图片分开存储到指定文件夹下
        可用参数 
        -s | size 分类文件大小
    """
    originPath = argv[0]  # 原始路径
    targetPath = argv[1]  # 目标路径
    print("originPath", originPath)
    print("targetPath", targetPath)
    try:
        opts, args = getopt.getopt(argv[2:], "-s:", ["size=", "help"])
    except getopt.GetoptError:
        print("参数错误")
        print(dec)
        sys.exit(2)

    for opt, arg in opts:
        if opt in ('-h', '--help'):
            print(dec)
            exit(0)
        elif opt in ("-s", "--size"):
            size = int(arg)
            print("输入的数值为", size)
            partitionFile(originPath, targetPath, size)
            exit(0)


if __name__ == "__main__":
    main(sys.argv[1:])
